package com.example.smartcity.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.smartcity.R;
import com.example.smartcity.search.FlowLayoutManager;
import com.example.smartcity.search.PhotoAdapter;
import com.example.smartcity.utils.APIConfig;
import com.example.smartcity.utils.ButtomMenuDialog;
import com.google.gson.Gson;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TakePhotoActivity extends AppCompatActivity {
    private Button btn_send;
    private Button btn_photo;
    private TextView tv;
    private ImageButton img;
    private Toolbar toolbar;
    private GridLayout rootLayout;
    Intent intent = null;
    private static int i=1;
    private RecyclerView photorecycler;
    private static List<Bitmap> bitmaps = new ArrayList<>();
    ImageView iv2;
    private List<ImageView> imageViewList = new ArrayList<>();
    private EditText content;
    private EditText title;
    int uid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_photo);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        btn_photo = findViewById(R.id.btn_photo);
        img = findViewById(R.id.img0);
        btn_send = findViewById(R.id.btn_send);
        content = findViewById(R.id.content);
        title = findViewById(R.id.title);
        /**
         * 解决android7调用照相机后直接奔溃问题
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
        checkPermission();
        initListener();
    }


    /**
     * 检查拍照权限,防止权限拒绝
     */
    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(TakePhotoActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 执行到这里表示没有访问权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(TakePhotoActivity.this, Manifest.permission.CAMERA)) {
                Toast.makeText(TakePhotoActivity.this,"禁止访问",Toast.LENGTH_LONG).show();
            } else {
                ActivityCompat.requestPermissions(TakePhotoActivity.this, new String[]{Manifest.permission.CAMERA}, 200);
            }
        } else {
            //takePhoto();
        }
    }
    private void changephotoCamera(){
        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 调用系统相机
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 400);   //有数据的返回
    }
    private void changephotoAlbum(){
        intent = new Intent();
        intent.setType("image/*");   //设定类型为image
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 300);//选中相片后返回本Activity
    }

    private void initListener() {

        // 顶部返回
        toolbar.setNavigationIcon(R.mipmap.top_bar_left_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        btn_send.setOnClickListener(new View.OnClickListener(){
            List<byte[]> byteLists = new ArrayList<>();
            List<String> nameLists = new ArrayList<>();
            @Override
            public void onClick(View v) {
                Log.i("imgviewlist",imageViewList.size()+"");
                for (ImageView imageView : imageViewList) {
                    Log.i("TFA","activated imageviewlist");
                    imageView.getDrawable();
                    Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);  // 质量为100，即不压缩

                    // 在这里处理imageView对象
                    byte[] bytes = baos.toByteArray();
                    byteLists.add(bytes);
                    Log.i("changedAvatar",bytes.toString());
                    // 创建HTTP连接并上传图片
                    SharedPreferences sharedPreferences = getSharedPreferences("token_data", MODE_PRIVATE);
                    uid = sharedPreferences.getInt("token", 1);
                    String imageName = "SUISHOUPAI"+generateRandomNumber()+"_"+uid+".png";
                    Log.i("suishoupaiimgname",imageName);
                    nameLists.add(imageName);
                }
                Gson gson = new Gson();
                String bytelistString = gson.toJson(byteLists);
                String nameListString = gson.toJson(nameLists);
                String contenttext = content.getText().toString();
                String titletext = title.getText().toString();
                String url = APIConfig.BASE_URL + "/suiShouPai/upload";
                OkHttpClient client = new OkHttpClient();
                MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
                MediaType mediaType = MediaType.parse("image/jpeg"); // 根据实际情况选择合适的媒体类型
                RequestBody requestBodyImage = RequestBody.create(mediaType, bytelistString);
                Log.i("projectionStr",nameListString);
                builder.addFormDataPart("files",bytelistString);
                builder.addFormDataPart("names", nameListString);
                builder.addFormDataPart("content",contenttext);
                builder.addFormDataPart("title",titletext);
                SharedPreferences sp = getSharedPreferences("token_data", Context.MODE_PRIVATE);
                uid = sp.getInt("token",1);
                builder.addFormDataPart("uid", String.valueOf(uid));
                MultipartBody multipartBody = builder.build();
                Log.i("avatarsend","发送了"+multipartBody.toString());
                Request request = new Request.Builder()
                        .url(url)
                        .post(multipartBody)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        runOnUiThread(() -> {
                            Toast toast = Toast.makeText(TakePhotoActivity.this, "发表失败", Toast.LENGTH_SHORT);
                            toast.show();
                        });
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()) {
                            runOnUiThread(() -> {
                                Toast toast = Toast.makeText(TakePhotoActivity.this, "发表成功", Toast.LENGTH_SHORT);
                                toast.show();
                                finish();
                            });
                        } else {
                            runOnUiThread(() -> {
                                Toast toast = Toast.makeText(TakePhotoActivity.this, "发布失败", Toast.LENGTH_SHORT);
                                toast.show();
                            });
                        }
                    }
                });
            }
        });
        img.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(TakePhotoActivity.this)
                        .setIcon(R.mipmap.picture)
                        .setMessage("插入图片")
                        .setPositiveButton("拍照", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                takePhoto();
                            }
                        })
                        .setNegativeButton("相册", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {chooseFromAlbum();}
                        })
                        .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
            }
        });
        // 按钮点击事件,单击弹出AlertDialog对话框
        btn_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(TakePhotoActivity.this)
                        .setIcon(R.mipmap.picture)
                        .setMessage("插入图片")
                        .setPositiveButton("拍照", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                takePhoto();
                            }
                        })
                        .setNegativeButton("相册", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {chooseFromAlbum();}
                        })
                        .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
            }
        });
    }

    /**
     * 获取图片
     */
    public void takePhoto() {//拍照新增
        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 调用系统相机
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 200);   //有数据的返回
    }

    /**
     * 选择相册
     */
    public void chooseFromAlbum() {//从相册新增
        intent = new Intent();
        intent.setType("image/*");   //设定类型为image
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 100);//选中相片后返回本Activity
    }


    /**
     * 重写onActivityResult方法：将返回的图片数据设置到ImageView上
     */

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();  //获取数据
            ContentResolver contentResolver = getContentResolver();
            Bitmap bitmap = null;
            Bundle extras = null;
            if (requestCode == 100) {//相册新增
                try {
                    bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri));  //将对象存入Bitmap中
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            if (requestCode == 200) {//拍照新增
                try {
                    if (uri != null){
                        bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri);  // 根据Uri获取Bitmap图片
                    } else{  // 从Bundle里面获取Bitmap图片
                        extras = data.getExtras();
                        bitmap = extras.getParcelable("data");
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (requestCode == 300){//相册修改？
                try {
                    bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri));  //将对象存入Bitmap中
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                int imgWidth = bitmap.getWidth();  //获取图片宽度
                int imgHeight = bitmap.getHeight();  // 获取图片高度
                double partion = imgWidth * 1.0 / imgHeight;
                double sqrtLength = Math.sqrt(partion * partion + 1);
                /**
                 * 设置图片新的缩略图大小
                 */
                double newImgW = 680 * (partion / sqrtLength);
                double newImgH = 680  * (1 / sqrtLength);
                float scaleW = (float) (newImgW / imgWidth);
                float scaleH = (float) (newImgH / imgHeight);
                Matrix mx = new Matrix();

                /**
                 * 对原图片进行缩放
                 */
                mx.postScale(scaleW, scaleH);
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, imgWidth, imgHeight, mx, true);
                bitmap = getBitmapWidth(bitmap);
                changeImageView(iv2, bitmap);
                return;
            }
            if (requestCode == 400){//拍照修改？
                try {
                    if (uri != null){
                        bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri);  // 根据Uri获取Bitmap图片
                    } else{  // 从Bundle里面获取Bitmap图片
                        extras = data.getExtras();
                        bitmap = extras.getParcelable("data");
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                int imgWidth = bitmap.getWidth();  //获取图片宽度
                int imgHeight = bitmap.getHeight();  // 获取图片高度
                double partion = imgWidth * 1.0 / imgHeight;
                double sqrtLength = Math.sqrt(partion * partion + 1);
                /**
                 * 设置图片新的缩略图大小
                 */
                double newImgW = 680 * (partion / sqrtLength);
                double newImgH = 680  * (1 / sqrtLength);
                float scaleW = (float) (newImgW / imgWidth);
                float scaleH = (float) (newImgH / imgHeight);
                Matrix mx = new Matrix();

                /**
                 * 对原图片进行缩放
                 */
                mx.postScale(scaleW, scaleH);
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, imgWidth, imgHeight, mx, true);
                bitmap = getBitmapWidth(bitmap);
                changeImageView(iv2, bitmap);
                return;
            }
            int imgWidth = bitmap.getWidth();  //获取图片宽度
            int imgHeight = bitmap.getHeight();  // 获取图片高度
            double partion = imgWidth * 1.0 / imgHeight;
            double sqrtLength = Math.sqrt(partion * partion + 1);

            /**
             * 设置图片新的缩略图大小
             */
            double newImgW = 680 * (partion / sqrtLength);
            double newImgH = 680  * (1 / sqrtLength);
            float scaleW = (float) (newImgW / imgWidth);
            float scaleH = (float) (newImgH / imgHeight);
            Matrix mx = new Matrix();
            /**
             * 对原图片进行缩放
             */
            mx.postScale(scaleW, scaleH);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, imgWidth, imgHeight, mx, true);
            bitmap = getBitmapWidth(bitmap);
            createImageView(bitmap);
            Log.i("photobit",bitmap.toString());
            //img.setImageBitmap(bitmap);

        }
    }
    public void createImageView(Bitmap bitmap){
        rootLayout = findViewById(R.id.imagelayout);
        // 创建一个ImageView对象
        ImageView imageView = new ImageView(this);
        imageView.setId(R.id.img0+Integer.valueOf(i));
        Log.i("imgid",R.id.img0+Integer.valueOf(i)+"");
        i++;
        // 设置ImageView的布局参数
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(dpToPx(20), dpToPx(20), 0, dpToPx(10));
        imageView.setLayoutParams(layoutParams);
        // 设置ImageView的图片资源
        imageView.setImageBitmap(bitmap);
        // 将ImageView添加到Activity的根布局中
        rootLayout.addView(imageView);
        imageView.findViewById(R.id.img0+Integer.valueOf(i));
        imageView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Log.i("imggid",imageView.getId()+"");
                //iv2.setId(imageView.getId());
                imageView.findViewById(imageView.getId());
                iv2 = imageView;
                new AlertDialog.Builder(TakePhotoActivity.this)
                        .setIcon(R.drawable.dialogicon)
                        .setMessage("更改图片")
                        .setPositiveButton("拍照", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                changephotoCamera();
                            }
                        })
                        .setNegativeButton("相册", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                changephotoAlbum();
                            }
                        })
                        .setNeutralButton("删除", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                rootLayout.removeView(imageView);
                                imageViewList.remove(imageView);
                            }
                        })
                        .create().show();
            }
        });
        imageViewList.add(imageView);
    }
    public void changeImageView(ImageView imageView,Bitmap bitmap){
        imageView.setImageBitmap(bitmap);
    }


    /**
     * 给图片加边框，并返回边框后的图片
     * @param bitmap
     * @return
     */
    public Bitmap getBitmapWidth(Bitmap bitmap) {
        float frameSize = 0.2f;
        Matrix matrix = new Matrix();
        // 用来做底图
        Bitmap mbitmap = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        // 设置底图为画布
        Canvas canvas = new Canvas(mbitmap);
        canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
        float scale_x = (bitmap.getWidth() - 2 * frameSize - 2) * 1f / (bitmap.getWidth());
        float scale_y = (bitmap.getHeight() - 2 * frameSize - 2) * 1f / (bitmap.getHeight());
        matrix.reset();
        matrix.postScale(scale_x, scale_y);

        // 减去边框的大小
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), matrix, true);

        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(1);
        paint.setStyle(Paint.Style.FILL);

        // 绘制底图边框
        canvas.drawRect(new Rect(0, 0, mbitmap.getWidth(), mbitmap.getHeight()),paint);
        // 绘制灰色边框
        paint.setColor(Color.GRAY);
        canvas.drawRect(new Rect((int) (frameSize), (int) (frameSize), mbitmap.getWidth() - (int) (frameSize), mbitmap.getHeight() - (int) (frameSize)), paint);
        canvas.drawBitmap(bitmap, frameSize + 2, frameSize + 2, paint);
        return mbitmap;
    }
    public int dpToPx(float dp) {
        float density = getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5f);
    }
    private byte[] toByteArray(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        return outputStream.toByteArray();
    }
    public static int generateRandomNumber() {
        Random random = new Random();
        int min = 1000000;
        int max = 9999999;
        return random.nextInt(max - min + 1) + min;
    }
}